<?php include APPPATH . 'classes/BaseController.php'; ?>
<?php
/**
 * User: Matrix
 * Date: 27/10/12
 */
class Panel extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('producto_model');
        $this->load->model('categoria_model');
        $this->load->model('comun_model');
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->library('upload');
    }

    public function index($codCategoria = 0)
    {
        $select_categoria = $this->input->post('select_categoria');
        $txt_buscar = $this->input->post('txt_buscar');
        if (isset($select_categoria) && $select_categoria != '') {
            $codCategoria = $select_categoria;
        }

        if (isset($txt_buscar) && $txt_buscar != '') {
            $codCategoria = -1;
        }

        $registros = $this->categoria_model->get_categoria($codCategoria, $txt_buscar);
        $categoria = $this->categoria_model->get_categoriaById($codCategoria);
        $totalProductos = 0;
        $totalCategorias = 0;
        foreach ($registros as $item):
            if ($item['tipo'] == 'producto') {
                $totalProductos++;
            } else {
                $totalCategorias++;
            }
        endforeach;

        $data['totalProductos'] = $totalProductos;
        $data['totalCategorias'] = $totalCategorias;
        if (count($categoria) >= 0) {
            if (count($categoria) == 0) {
                $data['crearProducto'] = "SI";
                $data['crearCategoria'] = "SI";
            } else {
                $data['crearProducto'] = ($categoria['codigoCategoriaPadre'] == 0) ? "SI" : "SI";
                $data['crearCategoria'] = ($categoria['codigoCategoriaPadre'] == 0) ? "SI" : "NO";
            }

        } else {
            $data['crearProducto'] = "NO";
            $data['crearCategoria'] = "NO";
        }
        $data['registros'] = $registros;
        $data['select_categoria'] = $codCategoria;
        $data['cmbCagetoria'] = $this->tep_get_category_tree();
        $data['txt_buscar'] = $txt_buscar;
        $menu['selectLabel'] = 'mostrar';
        $this->load->view('pages/admin/templates/header_admin', $menu);
        $this->load->view('pages/admin/v_lista', $data);
        $this->load->view('pages/admin/templates/footer');
    }

    public function ver($codCategoria = 0)
    {
        $select_categoria = $this->input->post('select_categoria');
        if ($select_categoria != "") {
            $this->index($select_categoria);
        } else {
            $this->index($codCategoria);
        }


    }

    public function nuevacategoria($codCategoria = 0)
    {
        $categoria = array();
        if ($codCategoria == 0) {
            $categoria['nombre'] = "Principal";
            $categoria['codigo'] = "0";
        } else {
            $categoria = $this->categoria_model->get_categoriaById($codCategoria);
        }
        $data['nombreCategoriaPadre'] = $categoria['nombre'];
        $data['codigoCategoriaPadre'] = $categoria['codigo'];

        $data['estado'] = '1';
        $data['opciones'] = array();
        $data['sugerencias'] = array();
        $menu['selectLabel'] = '';
        $data['accion'] = 'Nueva';
        $data['productos'] = array();
        $this->load->view('pages/admin/templates/header_admin', $menu);
        $this->load->view('pages/admin/categoria/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');
    }


    public function novedades()
    {

        $registros = $this->comun_model->get_novedades();
        $data['registros'] = $registros;
        $data['titulo'] = "Novedades";
        $data['crear'] = "/panel/crear_novedad";
        $data['editar'] = "/panel/editar_novedad";
        $data['eliminar'] = "/panel/delete_novedad";
        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/v_lista_novedades', $data);
        $this->load->view('pages/admin/templates/footer');
    }

    public function crear_novedad()
    {
        $data= array();
        $data['accion'] = 'Nueva';
        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/novedades/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');
    }

    public function editar_novedad($id)
    {
        $registro= $this->comun_model->get_novedadById($id);
        $data['accion'] = 'Editar';
        $data['registro'] = $registro;
        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/novedades/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');
    }


    public function grabar_novedad()
    {
        $data = array();
        $data['nombre'] = $this->input->post('nombre');
        $data['orden'] = $this->input->post('orden');
        $data['fecha'] = $this->input->post('fecha');
        $data['descripcion'] = $this->input->post('descripcion');
        $data['descripcion_corta'] = $this->input->post('descripcion_corta');

        if (trim($data['orden']) == "") {
            $data['orden'] = 99999;
        }

        $codigo = $this->input->post('codigo');

        $config['upload_path'] = UPLOAD_NOVEDADES_PATH;
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2048';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';
        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        $imagen = $this->input->post('imagen');
        if (count($imagen) > 0) {

            if ($this->upload->do_upload('imagen')) {
                $upload = ($this->upload->data());
                $data['imagen'] = $upload['orig_name'];
            } else {

            }
        }


        if (isset($codigo) && $codigo != '') {
            $this->db->update('novedades', $data, array('cod_novedad' => $codigo));
        } else {
            $this->db->insert('novedades', $data);
        }
        $this->novedades();
    }

    public function delete_novedad($id)
    {
        $data = array();
        $this->db->delete('novedades', array('cod_novedad' => $id));
        $this->novedades();
    }

    public function crear_sabias_que()
    {
        $data['registros'] = array();
        $data['titulo'] = "SABIAS QUE?";
        $data['guardar'] = "/panel/grabar_sabias_que";
        $data['regresar'] = "/panel/sabias_que";
        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/sabiasque/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');
        $this->sabias_que();
    }

    public function editar_sabias_que($id)
    {
        $registro = $this->comun_model->get_sabiasqueById($id);
        $data['registro'] = $registro;
        $data['titulo'] = "SABIAS QUE?";
        $data['guardar'] = "/panel/grabar_sabias_que";
        $data['regresar'] = "/panel/sabias_que";
        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/sabiasque/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');

    }

    public function crear_tips_interes()
    {
        $data['registros'] = array();
        $data['titulo'] = "TIPS DE INTERÉS";
        $data['guardar'] = "/panel/grabar_tips_interes";
        $data['regresar'] = "/panel/tips_interes";
        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/sabiasque/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');
        $this->sabias_que();
    }

    public function editar_tips_interes($id)
    {
        $registro = $this->comun_model->get_sabiasqueById($id);
        $data['registro'] = $registro;
        $data['titulo'] = "TIPS DE INTERÉS";
        $data['guardar'] = "/panel/grabar_tips_interes";
        $data['regresar'] = "/panel/tips_interes";
        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/sabiasque/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');

    }

    public function sabias_que()
    {

        $registros = $this->comun_model->get_sabiasque();
        $data['registros'] = $registros;
        $data['titulo'] = "SABIAS QUE?";
        $data['crear'] = "/panel/crear_sabias_que";
        $data['editar'] = "/panel/editar_sabias_que";
        $data['eliminar'] = "/panel/delete_sabias_que";
        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/v_lista_interes', $data);
        $this->load->view('pages/admin/templates/footer');
    }

    public function grabar_sabias_que()
    {
        $data = array();
        $data['titulo'] = $this->input->post('titulo');
        $data['tipo'] = "1";
        $data['contenido'] = $this->input->post('contenido');
        $codigo = $this->input->post('cod_blog');

        if (isset($codigo) && $codigo != '') {
            $this->db->update('blog', $data, array('cod_blog' => $codigo));
        } else {
            $this->db->insert('blog', $data);
        }
        $this->sabias_que();
    }

    public function delete_sabias_que($id)
    {
        $data = array();
        $this->db->delete('blog', array('cod_blog' => $id));
        $this->sabias_que();
    }

    public function tips_interes()
    {

        $registros = $this->comun_model->get_tips_interes();
        $data['registros'] = $registros;
        $data['titulo'] = "TIPS DE INTERÉS";
        $data['crear'] = "/panel/crear_tips_interes";
        $data['editar'] = "/panel/editar_tips_interes";
        $data['eliminar'] = "/panel/delete_tips_interes";
        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/v_lista_interes', $data);
        $this->load->view('pages/admin/templates/footer');
    }

    public function grabar_tips_interes()
    {
        $data = array();
        $data['titulo'] = $this->input->post('titulo');
        $data['tipo'] = "2";
        $data['contenido'] = $this->input->post('contenido');
        $codigo = $this->input->post('cod_blog');

        if (isset($codigo) && $codigo != '') {
            $this->db->update('blog', $data, array('cod_blog' => $codigo));
        } else {
            $this->db->insert('blog', $data);
        }
        $this->tips_interes();
    }

    public function delete_tips_interes($id)
    {
        $data = array();
        $this->db->delete('blog', array('cod_blog' => $id));
        $this->tips_interes();
    }

    public function nuevaLinea()
    {
        $data = array();
        $data['cod_producto'] = $this->input->post('codigo');
        $data['nombre_linea'] = $this->input->post('linea');
        $this->db->insert('producto_linea', $data);

        echo $this->db->insert_id();

    }

    public function deleteLinea()
    {
        $data = array();
        $data['cod_producto'] = $this->input->post('codigo');
        $linea = $this->input->post('linea');
        $result = explode("-", $linea);
        $this->db->delete('producto_linea', array('cod_linea' => $result[1]));
        $this->db->delete('producto_imagen', array('cod_linea' => $result[1]));

    }

    public function grabar_link()
    {
        $config['upload_path'] = UPLOAD_DESCARGA_PATH;
        $config['allowed_types'] = 'gif|jpg|png|pdf|jpeg|xls|xlsx|doc|docx';
        $config['max_size'] = '2048';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';

        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        $data['nombre'] = $this->input->post('nombre');
        $data['orden'] = $this->input->post('orden');
        $imagenProducto = $this->input->post('archivo');
        if (count($imagenProducto) > 0 && $this->upload->do_upload('archivo')) {
            $upload = ($this->upload->data());
            $data['archivo'] = $upload['orig_name'];
        }

        $this->db->insert('links', $data);

        $this->links();
    }

    public function editarcategoria($codCategoria = 0)
    {
        $data = array();
        $data = $this->categoria_model->get_categoriaById($codCategoria);
        $categoria = array();
        if ($data['codigoCategoriaPadre'] == 0) {
            $categoria['nombre'] = "Principal";
            $categoria['codigo'] = "0";
            $data['nombreCategoria'] = "Principal";
        } else {
            $codigoPadre = $data['codigoCategoriaPadre'];
            $categoria = $this->categoria_model->get_categoriaById($codigoPadre);
            $data['nombreCategoria'] = $data['nombre'];
        }
        $data['nombreCategoriaPadre'] = $data['nombreCategoria'];
        $data['accion'] = 'Editar';
        $menu['selectLabel'] = 'categoria_producto';

        $this->load->view('pages/admin/templates/header_admin', $menu);
        $this->load->view('pages/admin/categoria/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');
    }

    public function deletecategoria($codCategoria = 0)
    {
        $data = $this->categoria_model->get_categoriaById($codCategoria);
        $this->db->delete('categoria', array('cod_categoria' => $codCategoria));
        $this->index($data['codigoCategoriaPadre']);
    }

    public function grabar_categoria()
    {
        $config['upload_path'] = UPLOAD_CATEGORIAS_PATH;
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2048';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';
        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        $data['es_categoria'] = $this->input->post('estadoCategoria');
        $data['nom_categoria'] = $this->input->post('nombreCategoria');
        $data['orden_categoria'] = $this->input->post('ordenCategoria');
        $imagen = $this->input->post('imagenCategoria');
        if (count($imagen) > 0) {

            if ($this->upload->do_upload('imagenCategoria')) {
                $upload = ($this->upload->data());
                $data['imagen_categoria'] = $upload['orig_name'];
            } else {

            }
        }

        if (trim($data['orden_categoria']) == "") {
            $data['orden_categoria'] = 99999;
        }
        $codCategoria = $this->input->post('codigoCategoria');
        $data['cod_categoria_padre'] = $this->input->post('codigoCategoriaPadre');
        if (isset($codCategoria) && $codCategoria != '') {
            $this->db->update('categoria', $data, array('cod_categoria' => $codCategoria));
        } else {
            $this->db->insert('categoria', $data);
            $codCategoria = $this->db->insert_id();
        }
        if ($data['cod_categoria_padre'] != 0) {
            $this->ver($data['cod_categoria_padre']);
        } else {
            $this->index();
        }

    }

    public function nuevoproducto($codCategoria = 0)
    {
        $categoria = array();
        $data = array();
        $data["nom_producto"] = "-";
        $data["cod_categoria"] = -1;
        $this->db->insert('producto', $data);
        $codProducto = $this->db->insert_id();
        $data["codigo"] = $codProducto;
        if ($codCategoria == 0) {
            $categoria['nombre'] = "Principal";
            $categoria['codigo'] = "0";
        } else {
            $categoria = $this->categoria_model->get_categoriaById($codCategoria);
        }
        $data['nombreCategoriaPadre'] = $categoria['nombre'];
        $data['codigoCategoriaPadre'] = $categoria['codigo'];

        $data['estado'] = '1';
        $data['lineas'] = array();
        $menu['selectLabel'] = '';
        $data['accion'] = 'Nuevo';
        $data['codigoCategoriaPadre'] = $categoria['codigoCategoriaPadre'];
        $data['codigoCategoria'] = $categoria['codigo'];
        $this->load->view('pages/admin/templates/header_admin', $menu);
        $this->load->view('pages/admin/producto/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');
    }

    public function editarproducto($codProducto = 0)
    {
        $data = array();
        $data = $this->producto_model->get_productoById($codProducto);
        $categoria = array();
        if ($data['codigoCategoriaPadre'] == 0) {
            $categoria['nombre'] = "Principal";
            $categoria['codigo'] = "0";
            $data['nombreCategoria'] = "Principal";
        } else {
            $codigoPadre = $data['codigoCategoriaPadre'];
            $categoria = $this->categoria_model->get_categoriaById($codigoPadre);
            $data['nombreCategoria'] = $categoria['nombre'];
        }
        $data['nombreCategoriaPadre'] = $data['nombreCategoria'];
        $data['accion'] = 'Editar';

        $menu['selectLabel'] = 'categoria_producto';

        $this->load->view('pages/admin/templates/header_admin');
        $this->load->view('pages/admin/producto/v_editar', $data);
        $this->load->view('pages/admin/templates/footer');
    }

    public function deleteproducto($codProducto = 0)
    {
        $data = $this->producto_model->get_productoById($codProducto);
        $this->db->delete('producto', array('cod_producto' => $codProducto));
        $this->index($data['codigoCategoria']);
    }

    public function grabar_producto()
    {

        $config['upload_path'] = UPLOAD_PRODUCTO_PATH;
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2048';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';
        $this->load->library('upload', $config);
        $this->upload->initialize($config);


        $codProducto = $this->input->post('codigoProducto');
        $data['es_producto'] = $this->input->post('estadoProducto');
        $data['nom_producto'] = $this->input->post('nombreProducto');
        $data['cod_categoria'] = $this->input->post('codigoCategoria');
        $data['orden_producto'] = $this->input->post('ordenProducto');
        $data['desc_producto'] = $this->input->post('descripcion');

        $imagenPrincipal = $this->input->post('imagenPrincipal');
        if (count($imagenPrincipal) > 0) {

            if ($this->upload->do_upload('imagenPrincipal')) {
                $upload = ($this->upload->data());
                $data['imagen_principal_producto'] = $upload['file_name'];
            }
        }

        $imagenSecundaria = $this->input->post('imagenSecundaria');
        if (count($imagenSecundaria) > 0) {

            if ($this->upload->do_upload('imagenSecundaria')) {
                $upload = ($this->upload->data());
                $data['imagen_secundaria_producto'] = $upload['file_name'];
            }
        }

        if (trim($data['orden_producto']) == "") {
            $data['orden_producto'] = 99999;
        }

        $codigoCategoria = $data['cod_categoria'];

        $insert = false;
        if (isset($codProducto) && $codProducto != '') {
            $this->db->update('producto', $data, array('cod_producto' => $codProducto));
        } else {
            $this->db->insert('producto', $data);
            $codProducto = $this->db->insert_id();
            $insert = true;
        }

        $producto = array();
        $producto['cod_producto'] = $codProducto;
        $this->index($codigoCategoria);
    }

    private function grabarDetalle($codProducto,
                                   $lineaId,
                                   $detalleOrdenList,
                                   $detalleCodigoList,
                                   $fileNameAlias
    )
    {
        $total = count($detalleCodigoList);

        $insert = false;
        for ($i = 0; $i < $total; $i++) {
            $data = array();
            $data["cod_producto"] = $codProducto;
            $data["cod_linea"] = $lineaId;
            $data["orden_imagen"] = $detalleOrdenList[$i];
            if (trim($data["orden_imagen"]) == "") {
                $data["orden_imagen"] = ($i + 1);
            }

            if ($detalleCodigoList[$i] == "") {
                $data["nombre_imagen"] = $this->uploadImagen(UPLOAD_PRODUCTO_PATH, $fileNameAlias . ($i));
                $insert = true;
            } else {
                $insert = false;
            }

            if ($insert) {
                if (isset($data["nombre_imagen"]) && $data["nombre_imagen"] != "") {
                    $this->db->insert('producto_imagen', $data);
                }
            } else {
                $this->db->update('producto_imagen', $data, array('cod_imagen' => $detalleCodigoList[$i]));
            }
        }
    }

    private function uploadImagen($path, $fileInput)
    {
        $config['upload_path'] = $path;
        $config['allowed_types'] = 'gif|jpg|png|pdf|jpeg|xls|xlsx|doc|docx';
        $config['max_size'] = '5096';
        $config['max_width'] = '10240';
        $config['max_height'] = '7680';
        $this->upload->initialize($config);

        if (!$this->upload->do_upload($fileInput)) {
            return "";
        } else {
            $upload = ($this->upload->data());
            return $upload['file_name'];
        }
    }

    function tep_get_category_tree($parent_id = '0', $spacing = '', $exclude = '', $category_tree_array = '')
    {

        if (!is_array($category_tree_array)) $category_tree_array = array();
        if ((sizeof($category_tree_array) < 1) && ($exclude != '0')) $category_tree_array[''] = 'PRINCIPIO';

        $categories_query = $this->categoria_model->get_subcategoriaById($parent_id);


        foreach ($categories_query as $categories) {
            if ($exclude != $categories['codigo']) $category_tree_array[$categories['codigo']] = $spacing . $categories['nombre'];
            $category_tree_array = $this->tep_get_category_tree($categories['codigo'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $category_tree_array);
        }

        return $category_tree_array;
    }


}

?>